# -*- coding: utf-8 -*-

"""
    This file is part of Free Herbarium.

    Free Herbarium is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Free Herbarium is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Free Herbarium.  If not, see <http://www.gnu.org/licenses/>.
"""

import re

from lib.preprocessor import Preprocessor

class UnknownNameException:
      """ The name of a given species is not given. It must be."""
      def __init__(self, value):
          self.value = value
          
      def __str__(self):
          return repr(self.value)
    
class FHBparser:
      """Parses a file with all the species and rendering data. """
      
      def __init__(self, source):
          self.source = source
          
      def _getname(self,defs):
          """ Tries to access the name of a species. If none given,
              raises an exception. """
          for d in defs:
              if d.split("=")[0] == "NAME":
                 return d.split("=")[1]
          raise UnknownNameException("No NAME parameter found")
        
      def _checkDict(self, defs):
          """ Checks if the dictionary of the species has been initialized.
              If not, it initializes it. """
          if self.curname not in self.dictionary.keys():
             n = self._getname(defs)
             self.dictionary[self._getname(defs)] = []
             self.curname = n
          
      def parse(self):
          """ The main job. Parses the document. """
          with open(self.source) as f:
               text = f.read()
               
          preprocessor = re.findall("#(.*?)$",text,re.M)
          preprocess = Preprocessor(preprocessor)
          preprocess.save()
          
          for x in preprocessor:
              text = text.replace("#"+x+"\n","") 
          text = text.replace("\n","")
          parsed = text.split("BeginSpecies")[1:]
          
          self.dictionary = {}
          
          for sp in parsed:
              defs = sp.split(";")
              self.curname = ""
              for defi in defs:
                  stat = defi.split("=")
                  sw = stat[0]
                  if sw == "EndSpecies": break
                  val = stat[1]
                  if sw == "NAME":
                     self.dictionary[val] = {}
                     self.curname = val
                  elif sw == "OTHERNAMES":
                     self._checkDict(defs)
                     self.dictionary[self.curname]["othernames"] = re.split(",\s?",val)
                  elif sw == "IMGS":
                     self._checkDict(defs)
                     self.dictionary[self.curname]["imgs"] = re.split(",\s?",val)
                  elif sw == "LAT":
                     self._checkDict(defs)
                     self.dictionary[self.curname]["lat"] = val
                  elif sw == "DESC":
                     self._checkDict(defs)
                     self.dictionary[self.curname]["desc"] = val
                  elif sw == "ES":
                     self._checkDict(defs)
                     self.dictionary[self.curname]["es"] = val
                  elif sw == "FAM":
                     self._checkDict(defs)
                     self.dictionary[self.curname]["fam"] = val
                  else:
                     print "<Warning> Unrecognized variable \"%s\" with value \"%s\"" % (sw, val)
                  
          return self.dictionary
          
          